package com.cskaoyan.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cskaoyan.exceptionJY.CodeErrorException;
import com.cskaoyan.exceptionJY.PhoneNumberException;
import com.cskaoyan.exceptionJY.PhoneNumberNotExitsException;
import com.cskaoyan.exceptionJY.UsernameRepeatException;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.model.bean.User;
import com.cskaoyan.model.bo.LoginBo;
import com.cskaoyan.model.bo.systembo.CodeBo;
import com.cskaoyan.model.bo.systembo.RegisterBo;
import com.cskaoyan.model.bo.systembo.ResetBo;
import com.cskaoyan.model.vo.systemvo.RegisterVo;
import com.cskaoyan.model.vo.systemvo.UserInfo;
import com.cskaoyan.model.vo.systemvo.WxLoginVo;
import com.cskaoyan.utils.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void regCaptcha(CodeBo codeBo) throws PhoneNumberException {
        //验证手机号格式
        if (codeBo.getMobile().length() != 11){
            throw new PhoneNumberException();
        }
        String accessKeyId = "LTAI5tEerWnvPUB3RgYijtKp";
        String accessKeySecret = "hBZyT8Bvqb5wjSCAdN0ZhYQw2fhXGw";
        //短信服务的签名
        String signName = "stone4j";
        //发送短信模板的代码
        String templateCode = "SMS_173765187";
        //生成随机6位数
        int randomCode = (int)((Math.random()*9+1)*100000);
        String mobile = codeBo.getMobile();

        //构造profile
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        //要求传json数据
        request.putQueryParameter("TemplateParam", "{\"code\":\""+ randomCode +"\"}");

        userMapper.insertMobileAndName(mobile,randomCode);

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public RegisterVo register(RegisterBo registerBo) throws Exception {
        //是否已经注册
        List<String> usernameList = userMapper.selectAllUsername();
        for (String username : usernameList) {
            if (username.equals(registerBo.getMobile())){
                throw new UsernameRepeatException();
            }
        }
        //比较验证码
        int code = userMapper.selectCodeByMobile(registerBo.getMobile());
        String codeS = String.valueOf(code);
        if (!codeS.equals(registerBo.getCode())){
            throw new CodeErrorException();
        }
        registerBo.setPassword(Md5Utils.getMd5(registerBo.getPassword()));
        //插入数据
        User user = new User();
        user.setUsername(registerBo.getUsername());
        user.setPassword(registerBo.getPassword());
        user.setLastLoginTime("now");
        user.setMobile(registerBo.getMobile());
        user.setAddTime("now");
        user.setDeleted(false);
        user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        user.setNickname(registerBo.getUsername());
        userMapper.insertSelective(user);

        RegisterVo registerVo = new RegisterVo();
        registerVo.setToken((String) SecurityUtils.getSubject().getSession().getId());
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(userMapper.selectNickNameByUserName(registerBo.getUsername()));
        userInfo.setAvatarUrl(userMapper.selectAvatarByUserName(registerBo.getUsername()));
        registerVo.setUserInfo(userInfo);
        return registerVo;
    }

    @Override
    public void reset(ResetBo resetBo) throws CodeErrorException, PhoneNumberNotExitsException {
        //检查手机号是否已经注册
        List<String> allMobile = userMapper.selectAllUsername();
        for (String mobile : allMobile) {
            if (mobile.equals(resetBo.getMobile())){
                //校验验证码
                int code = userMapper.selectCodeByMobile(resetBo.getMobile());
                String codeS = String.valueOf(code);
                if (!codeS.equals(resetBo.getCode())){
                    throw new CodeErrorException();
                }
                //修改密码
                userMapper.updatePasswordByMobile(resetBo.getMobile(),resetBo.getPassword());
                return;
            }
        }
        throw new PhoneNumberNotExitsException();
    }

    @Override
    public WxLoginVo login(LoginBo loginBo) {
        WxLoginVo wxLoginVo = new WxLoginVo();
        UserInfo userInfo = new UserInfo();

        userInfo.setNickName(userMapper.selectNickNameByUserName(loginBo.getUsername()));
        userInfo.setAvatarUrl(userMapper.selectAvatarByUserName(loginBo.getUsername()));

        wxLoginVo.setToken((String) SecurityUtils.getSubject().getSession().getId());
        wxLoginVo.setTokenExpire("2021-04-16T20:57:25.792");
        wxLoginVo.setUserInfo(userInfo);

        return wxLoginVo;

    }
}
